//
//  GMVideoExerciseVC.m
//  Teecloud
//
//  Created by xhkj on 2018/11/20.
//  Copyright © 2018 小志. All rights reserved.
//

#import "GMVideoExerciseVC.h"
#import "GMExamModel.h"
#import "GMSubjectsModel.h"
#import "GMVideoExerciseCell.h"
#import "GMVideoCardCell.h"
@interface GMVideoExerciseVC ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionview;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) GMExamModel *baseModel;
@end

@implementation GMVideoExerciseVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.collectionview registerNib:[UINib nibWithNibName:@"GMVideoExerciseCell" bundle:nil] forCellWithReuseIdentifier:@"GMVideoExerciseCell"];
    [self.collectionview registerNib:[UINib nibWithNibName:@"GMVideoCardCell" bundle:nil] forCellWithReuseIdentifier:@"GMVideoCardCell"];
    for (GMSubjectsModel *subModel in self.stuModel.Subjects) {
        subModel.examId = self.stuModel.Id;
    }
    [self.dataArr removeAllObjects];
    [self.dataArr addObjectsFromArray:self.stuModel.Subjects];
}
-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArr.count+1;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    kWeakObject(self)
    if (indexPath.row == self.dataArr.count) {
        GMVideoCardCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GMVideoCardCell" forIndexPath:indexPath];
        cell.model = self.baseModel;
        [cell.gotoBtn addTarget:self action:@selector(closePopView) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else{
        GMVideoExerciseCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GMVideoExerciseCell" forIndexPath:indexPath];
        GMSubjectsModel *subModel = self.dataArr[indexPath.row];
        cell.model = subModel;
        cell.index = indexPath.row+1;
        cell.total = self.dataArr.count;
        /**下一题*/
        cell.nextBlock = ^() {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row+1 inSection:0] atScrollPosition:(UICollectionViewScrollPositionRight) animated:YES];
//            });
              [collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row+1 inSection:0] atScrollPosition:(UICollectionViewScrollPositionRight) animated:YES];
        };
        /**上一题*/
        cell.lastBlock = ^() {
             [collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:0] atScrollPosition:(UICollectionViewScrollPositionLeft) animated:YES];
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:0] atScrollPosition:(UICollectionViewScrollPositionLeft) animated:YES];
//            });
        };
        /**提交所有答案*/
        cell.sumbitBlock = ^{
            for (GMSubjectsModel *subModel in self.dataArr) {
                if (kIsEmptyString(subModel.Answer)) {
                    //如果有题目未答，提醒
                    UIAlertController *alert  = [UIAlertController zj_alertControllerWithTitle:@"" message:@"还有题目未作答，继续提交吗？" optionStyle:OptionStyleStyleOK_Cancel OkTitle:@"确定" cancelTitle:@"取消" okBlock:^{
                        [weakself handerOK];
                    } cancelBlock:^{
                        
                    }];
                    [weakself presentViewController:alert animated:YES completion:nil];
                    /**找到如果有题目未答，直接退出循环*/
                    return;
                }
                
            }
            //如果全答完
            [weakself handerOK];
        };
        return cell;
    }
}
   
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.view.frame.size.width,self.view.frame.size.height);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
-(void)handerOK{
    NSMutableArray *sumbitArr = [[NSMutableArray alloc] init];
    for (NSInteger i =0; i<self.dataArr.count; i++) {
        GMSubjectsModel *subModel = self.dataArr[i];
        NSDictionary *sumbitDict = @{@"Id":subModel.Id,
                                     @"SortNo":subModel.SortNo,
                                     @"Answer":subModel.Answer?subModel.Answer:@"",
                                     @"StartTime":subModel.StartTime?subModel.StartTime:@"",
                                     @"UseTime":subModel.UseTime?subModel.UseTime:@""
                                     };
        [sumbitArr addObject:sumbitDict];
    }
    NSString *jsonString = sumbitArr.mj_JSONString;
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"resId":self.resId,
                          @"timeId":self.stuModel.Id,
                          @"subjectData":jsonString
                          };
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=PostExamInStudy&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                GMExamModel *model = [GMExamModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                self.baseModel = model;
                [MBProgressHUD showErrorOrSuc:@"提交成功" toView:self.view];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                     [self.collectionview scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.dataArr.count inSection:0] atScrollPosition:(UICollectionViewScrollPositionRight) animated:YES];
                     [[NSNotificationCenter defaultCenter] postNotificationName:@"postData" object:model];
                });
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:self.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:self.view];
        }
    }];
}
- (void)closePopView{
    //发送通知继续播放，然后关闭弹出视图
     [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoPlay" object:nil];
     [self dismissViewControllerAnimated:YES completion:nil];
}
@end
